/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utiles;

import java.io.IOException;
import java.net.URI;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 *
 * @author fcarou
 */
public class HttpHelper
{
    private String base;
    
    public HttpHelper (String base)
    {
        this.base = base;
    }
    
    public String doGet (String path, Header header, List<NameValuePair> params)
    {
        try
        {            
            URIBuilder builder = new URIBuilder (base + path);
            
            if (params != null)
                builder.addParameters(params);
            
            HttpClient client = HttpClients.createDefault();
            HttpGet get = new HttpGet (builder.build());
            
            if (header != null)
                get.setHeader(header);
            
            HttpResponse res = client.execute(get);
            HttpEntity entity = res.getEntity();
            
            if (entity != null)
                return EntityUtils.toString(entity);
        }
        catch (HttpHostConnectException ex)
        {
            System.exit(0);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
        return null;
    }
    
    public String doPost (String path, Header header, String parametro)
    {
        try
        {
            HttpClient client = HttpClients.createDefault();
            HttpPost post = new HttpPost(base + path);

            if (header != null)
                post.setHeader(header);
            
            StringEntity entity = new StringEntity(parametro);
            post.setEntity(entity);
            post.setHeader("Accept", "application/json");
            post.setHeader("Content-type", "application/json");
            
            HttpResponse res = client.execute(post);
            HttpEntity resEntity = res.getEntity();
            
            return EntityUtils.toString(resEntity);
        }
        catch (HttpHostConnectException ex)
        {
            System.exit(0);
        }
        catch (Exception e)
        {
            
        }
        
        return null;
    }
}
